package org.linlinjava.litemall.admin.web;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.dto.GoodsAllinone;
import org.linlinjava.litemall.admin.service.AdminGoodsService;
import org.linlinjava.litemall.core.storage.AliyunStorage;
import org.linlinjava.litemall.core.storage.Storage;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.dao.LitemallStorageMapper;
import org.linlinjava.litemall.db.domain.LitemallGoods;
import org.linlinjava.litemall.db.domain.LitemallStorage;
import org.linlinjava.litemall.db.service.LitemallStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.*;

@RestController
@RequestMapping("/admin/goods")
@Validated
public class AdminGoodsController {
    private final Log logger = LogFactory.getLog(AdminGoodsController.class);
    //    private final static String ACCESS_KEY_ID = "LTAI4FcYGTDfTjRbbchGB4Td";
//    private final static String ACCESS_KEY_SECRET = "pzZ4dtZWzHDR1hCTJiMACMLIzksjG4";
//    private final static String BUCKET_NAME = "tianbwpdf";
//    private final static String ENDPOINT = "http://oss-cn-hangzhou.aliyuncs.com";
//    private static OSS client = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    @Autowired
    private AdminGoodsService adminGoodsService;
    @Autowired
    private LitemallStorageMapper litemallStorageMapper;
    @Autowired
    private AliyunStorage aliyunStorage;
    /**
     * 查询商品
     *
     * @param goodsId
     * @param goodsSn
     * @param name
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    @RequiresPermissions("admin:goods:list")
    @RequiresPermissionsDesc(menu = {"商品管理", "商品管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(Integer goodsId, String goodsSn, String name,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        return adminGoodsService.list(goodsId, goodsSn, name, page, limit, sort, order);
    }

    @GetMapping("/catAndBrand")
    public Object list2() {
        return adminGoodsService.list2();
    }

    /**
     * 编辑商品
     *
     * @param goodsAllinone
     * @return
     */
    @RequiresPermissions("admin:goods:update")
    @RequiresPermissionsDesc(menu = {"商品管理", "商品管理"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody GoodsAllinone goodsAllinone) {

        return adminGoodsService.update(goodsAllinone);
    }

    /**
     * 删除商品
     *
     * @param goods
     * @return
     */
    @RequiresPermissions("admin:goods:delete")
    @RequiresPermissionsDesc(menu = {"商品管理", "商品管理"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody LitemallGoods goods) {
        return adminGoodsService.delete(goods);
    }

    /**
     * 添加商品
     *
     * @param goodsAllinone
     * @return
     */
    @RequiresPermissions("admin:goods:create")
    @RequiresPermissionsDesc(menu = {"商品管理", "商品管理"}, button = "上架")
    @PostMapping("/create")
    public Object create(@RequestBody GoodsAllinone goodsAllinone) {
        return adminGoodsService.create(goodsAllinone);
    }

    @RequiresPermissions("admin:goods:download")
    @RequiresPermissionsDesc(menu = {"商品管理", "商品管理"}, button = "下载")

    @GetMapping("/download")
    public Object download(String query) {
        //OutputStream toClient=null;
        // InputStream  bis = null;
        try {

            LitemallStorage sto = litemallStorageMapper.findByUrl(query);

            String name = sto.getName();
            String keyName = sto.getKey();
            File targetFile = new File("C:/pdf/"+name);

            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            aliyunStorage.donlowd(keyName,targetFile);

            //TODO
            //优化代码,未调通
            // InputStream input = aliyunStorage.donlowd("23fekb48lccjk62w1r8l.pdf");
            // String shareUrl = goods.getShareUrl();
            //       InputStream input = object.getObjectContent();
            //       bis = new BufferedInputStream(input);
            //          response.reset();
            //           toClient = new BufferedOutputStream(response.getOutputStream());

//            response.setContentType("application/octet-stream");
//            response.setHeader("Content-Length", String.valueOf(input.available()));
//            response.setHeader("Content-Disposition","attach;filename=" + "123.pdf");
//            int number=0;
//            byte[] buffer = new byte[1024];
//            while ((number = bis.read(buffer)) != -1){
//                //response.getOutputStream().write(buffer, 0, number);
//                toClient.write(buffer,0,number);
//            }
            // toClient.flush();
            //response.getOutputStream().close();
            // input.close();
            return ResponseUtil.ok();

           /* byte[] buffer = new byte[input.available()];
            response.addHeader("Content-Disposition", "attachment;filename=" + "123.pdf");
            response.setContentType("application/pdf");
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
            toClient.close();*/
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
//            try {
//                if(null !=toClient){
//                    toClient.close();
//                }
//                if(null !=bis){
//                    bis.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        }
        return ResponseUtil.ok();

    }
    /**
     * 商品详情
     *
     * @param id
     * @return
     */
    @RequiresPermissions("admin:goods:read")
    @RequiresPermissionsDesc(menu = {"商品管理", "商品管理"}, button = "详情")
    @GetMapping("/detail")
    public Object detail(@NotNull Integer id) {
        return adminGoodsService.detail(id);

    }

}
